using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;
using System.Text;

namespace BlazeApps.Library.Form
{
    [Serializable()]
    public class FormAnswerDetail : Csla.BusinessBase<FormAnswerDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _formResponseID = Guid.Empty;
        private Guid _formQuestionID = Guid.Empty;
        private Guid _formAnswerID = Guid.NewGuid();
        private string _answer = string.Empty;
        private bool _hasData = false;

        public Guid FormResponseID
        {
            get
            {
                CanReadProperty("FormResponseID", true);
                return _formResponseID;
            }
            set
            {
                CanWriteProperty("FormResponseID", true);
                if (!_formResponseID.Equals(value))
                {
                    _formResponseID = value;
                    PropertyHasChanged("FormResponseID");
                }
            }
        }

        public Guid FormQuestionID
        {
            get
            {
                CanReadProperty("FormQuestionID", true);
                return _formQuestionID;
            }
            set
            {
                CanWriteProperty("FormQuestionID", true);
                if (!_formQuestionID.Equals(value))
                {
                    _formQuestionID = value;
                    PropertyHasChanged("FormQuestionID");
                }
            }
        }

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid FormAnswerID
        {
            get
            {
                CanReadProperty("FormAnswerID", true);
                return _formAnswerID;
            }
        }

        public string Answer
        {
            get
            {
                CanReadProperty("Answer", true);
                return _answer;
            }
            set
            {
                CanWriteProperty("Answer", true);
                if (value == null)
                    value = string.Empty;
                if (!_answer.Equals(value))
                {
                    _answer = value;
                    PropertyHasChanged("Answer");
                }
            }
        }

        public Boolean HasData
        {
            get
            {
                return _hasData;
            }
        }

        protected override object GetIdValue()
        {
            return _formAnswerID;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // Answer
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "Answer");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in FormAnswerDetail
            //AuthorizationRules.AllowRead("FormQuestionID", "FormAnswerDetailReadGroup");
            //AuthorizationRules.AllowRead("FormAnswerID", "FormAnswerDetailReadGroup");
            //AuthorizationRules.AllowRead("Answer", "FormAnswerDetailReadGroup");

            //AuthorizationRules.AllowWrite("Answer", "FormAnswerDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in FormAnswerDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("FormAnswerDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in FormAnswerDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("FormAnswerDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in FormAnswerDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("FormAnswerDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in FormAnswerDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("FormAnswerDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private FormAnswerDetail()
        { /* require use of factory method */
        }

        public static FormAnswerDetail NewFormAnswerDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a FormAnswerDetail");
            return DataPortal.Create<FormAnswerDetail>();
        }

        public static FormAnswerDetail GetFormAnswerDetail(Guid formAnswerID)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a FormAnswerDetail");
            return DataPortal.Fetch<FormAnswerDetail>(new Criteria(formAnswerID));
        }

        public static FormAnswerDetail GetFormAnswerDetail(Guid FormQuestionID, Guid FormResponseID)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a FormAnswerDetail");
            return DataPortal.Fetch<FormAnswerDetail>(new Criteria(FormQuestionID, FormResponseID));
        }

        public static void DeleteFormAnswerDetail(Guid formAnswerID)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a FormAnswerDetail");
            DataPortal.Delete(new Criteria(formAnswerID));
        }

        public override FormAnswerDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a FormAnswerDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a FormAnswerDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a FormAnswerDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid FormAnswerID;

            public Criteria(Guid formAnswerID)
            {
                this.FormAnswerID = formAnswerID;
            }

            public Guid FormQuestionID = Guid.Empty;
            public Guid FormResponseID = Guid.Empty;

            public Criteria(Guid FormQuestionID, Guid FormResponseID)
            {
                this.FormQuestionID = FormQuestionID;
                this.FormResponseID = FormResponseID;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            if (criteria.FormQuestionID != Guid.Empty && criteria.FormResponseID != Guid.Empty)
            {
                DAL.AddParameter("@FormQuestionID", criteria.FormQuestionID);
                DAL.AddParameter("@FormResponseID", criteria.FormResponseID);

                using (SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetAnswerByQuestionIDAndResponseID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
                {
                    FetchObject(dr);
                    ValidationRules.CheckRules();

                    //load child object(s)
                    FetchChildren(dr);
                }
            }
            else
            {
                DAL.AddParameter("@FormAnswerID", criteria.FormAnswerID);

                using (SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetAnswerByQuestionIDAndResponseID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
                {
                    FetchObject(dr);
                    ValidationRules.CheckRules();

                    //load child object(s)
                    FetchChildren(dr);
                }
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            if (dr.Read())
            {
                _formResponseID = dr.GetGuid("FormResponseID");
                _formQuestionID = dr.GetGuid("FormQuestionID");
                _formAnswerID = dr.GetGuid("FormAnswerID");
                _answer = dr.GetString("Answer");
                _hasData = true;
            }
            else
            {
                _hasData = false;
            }
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert

        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertAnswer.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@FormResponseID", _formResponseID);
            DAL.AddParameter("@Answer", _answer);
            DAL.AddParameter("@FormQuestionID", _formQuestionID);
            DAL.AddParameter("@FormAnswerID", _formAnswerID);
        }

        #endregion //Data Access - Insert

        #region Data Access - Update

        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateAnswer.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@FormResponseID", _formResponseID);
            DAL.AddParameter("@FormQuestionID", _formQuestionID);
            DAL.AddParameter("@FormAnswerID", _formAnswerID);
            DAL.AddParameter("@Answer", _answer);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_formAnswerID));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteAnswer.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@FormAnswerID", DbType.Guid, criteria.FormAnswerID);
        }

        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
